package util;

import exception.DataAccessException;

import java.sql.*;

public class JdbcUtil {

    public static String driverClassName="com.mysql.jdbc.Driver";
    public static String url="jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf8";
    public static String username="root";
    public static String password="123";

    static {
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("JdbcUtil初始化失败");
        }
    }

    public static Connection getConnection(){
        Connection con=null;

        try {
            con= DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DataAccessException("数据访问失败",e);
        }

        return con;
    }

    public static void close(Connection con, PreparedStatement ps, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }



}
